package top.lbqaq.dao;

import top.lbqaq.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author luoboQAQ
 * @Date 2021/11/21
 */
public class UserDao {
    public User getLoginUser(Connection connection, String username) throws SQLException {
        User user = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;

        if (connection != null) {
            String sql = "select u.id,u.username,u.password,u.role_id,r.role_name " +
                    "from user u,role r " +
                    "where u.role_id=r.role_id " +
                    "and username = ?";
            Object[] params = {username};
            rs = BaseDao.execute(connection, pstm, rs, sql, params);
            if (rs.next()) {
                user = new User();
                user.setId(rs.getLong("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRoleId(rs.getLong("role_id"));
                user.setRoleName(rs.getString("role_name"));
            }
            BaseDao.closeResource(null, pstm, rs);

        }
        return user;
    }

    public int insertUser(Connection connection, User user) throws SQLException {
        PreparedStatement pstm = null;
        int end = 0;
        if (connection != null) {
            String sql = "insert into user(username, `password`, role_id) values(?,?,?)";
            Object[] params = {user.getUsername(), user.getPassword(), user.getRoleId()};
            end = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
        }
        return end;
    }
}
